<?php

namespace app\controllers\h5;

use app\controllers\h5\base\H5Controller;
use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\product\Product;
use app\models\product\ProductArea;
use app\models\product\ProductAreaList;
use app\models\SetUserUp;
use app\models\user\User;
use app\models\user\UserCart as Model;
use app\models\user\UserLevel;

/**
 * Class CartController
 * @package app\controllers\h5
 */
class CartController extends H5Controller
{
    // 检测是否买过相同商品
    public function actionCheckBuy()
    {

        // debug
        return $this->successEncode(['result' => false]);

        $product_id = $this->post('id');
        $product = Product::findOne(['id' => $product_id]);
        if (!$product) {
            return $this->fail('错误~~~');
        }

        // var_dump($product_id);exit;

        $area_id = ProductAreaList::find()
            ->where(['product_id' => $product_id])
            ->select(['area_id'])
            ->scalar();

        $is = ProductArea::$KEY['REPORT'] == $area_id;

        // var_dump($is);exit;

        // 处理复购, 手动调身份
        // $has_order = false;

        if ($is) {
            // 检查是否买过相同订单
            $items = OrderItem::find()
                ->where(['product_id' => $product->id])
                ->select(['order_id'])
                ->column();
            // var_dump($items);exit;

            $order = Order::find()
                ->where(['id' => $items])
                ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
                ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
                ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
                ->andWhere(['!=', 'status', Order::$statusMapping['REFUND']])
                ->andWhere(['user_id' => $this->user->id])
                ->one();
            if ($order) {

                $has_order = true;

                return $this->successEncode(['result' => true]);
            }
        }

        // 商品价格与身份对比

        // if ($is && $has_order) {
        if ($is) {
            $set = SetUserUp::getLastOne();
            $level = User::find()
                ->select(['level'])
                ->where(['id' => $this->user->id])
                ->scalar();
            if ($product->price == $set->vip1) {
                if ($level >= UserLevel::$keys['vip1']) {
                    return $this->successEncode(['result' => true]);
                }
            } else if ($product->price == $set->svip1) {
                if ($level >= UserLevel::$keys['svip1']) {
                    return $this->successEncode(['result' => true]);
                }
            } else if ($product->price == $set->svip2) {
                if ($level >= UserLevel::$keys['svip2']) {
                    return $this->successEncode(['result' => true]);
                }
            } else if ($product->price == $set->svip3) {
                if ($level >= UserLevel::$keys['svip3']) {
                    return $this->successEncode(['result' => true]);
                }
            }
        }

        return $this->successEncode(['result' => false]);
    }

    // 添加到购物车与复购
    public function actionCheckRepeat()
    {
        // 报单区不能加入到购物车
        $product_id = $this->post('id');
        $product = Product::findOne(['id' => $product_id]);
        if (!$product) {
            return $this->fail('错误~~~');
        }

        // var_dump($product_id);exit;

        $area_id = ProductAreaList::find()
            ->where(['product_id' => $product_id])
            ->select(['area_id'])
            ->scalar();

        $is = ProductArea::$KEY['REPORT'] == $area_id;
        $is2 = ProductArea::$KEY['NEW1'] == $area_id;
        if ($is || $is2) {

            // 如果不是添加到购物车
            $no_add = $this->post('no_add', false);
            if (!$no_add) {
                return $this->fail('报单商品不能添加到购物车!');
            }
        }


        $id = $this->post('id');
        if (ProductArea::checkRepeat($id)) {
            $user = User::findOne(['id' => $this->user->id]);
            if ($user->level <= 0) {
                return $this->fail('您还没有报单, 不能复购!');
            }
        }


        return $this->success();
    }

    public function actionAddCart()
    {
        $user_id = $this->user->id;
        $product_id = $this->post('product_id');
        $quantity = intval($this->post('quantity', 1));
        $price = floatval($this->post('price'));
        $score_cost = floatval($this->post('score_cost'));

        // 推三返一处理
        if (ProductAreaList::checkInArea($product_id, Product::$areaMap['REPORT'])) {
            $p = Product::findOne(['id' => $product_id]);
            $set = SetUserUp::getLastOne();
            if ($p->price == $set->svip1) {
                return $this->fail('该商品不能加入购物车,请直接购买!');
            }
        }

        // sku
        $product_sku_id = $this->post('product_sku_id', 0);
        $selected_sku_value = json_encode($this->post('selected_sku_value', []));
        $selected_sku_text = json_encode($this->post('selected_sku_text', []));

        if ($product_sku_id) {
            $model = Model::findOne(['user_id' => $user_id, 'product_id' => $product_id, 'product_sku_id' => $product_sku_id]);
        } else {
            $model = Model::findOne(['user_id' => $user_id, 'product_id' => $product_id]);
        }
        if ($model) {
            $model->quantity += $quantity;
        } else {
            $model = new Model();
            $model->product_id = $product_id;
            $model->user_id = $user_id;
            $model->quantity = $quantity;
            $model->price = $price;
            $model->score_cost = $score_cost;
            if ($product_sku_id) {
                $model->product_sku_id = $product_sku_id;
                $model->selected_sku_value = $selected_sku_value;
                $model->selected_sku_text = $selected_sku_text;
            }
        }

        if ($model->save()) {
            return $this->success('添加成功');
        }

        return $this->fail();
    }

    public function actionList()
    {
        $list = Model::find()
            ->where(['user_id' => $this->user->id])
            // ->with(['product', 'product.mainImage', 'product.area'])
            ->with([
                'product', 'product.mainImage', 'product.area', 'product.area.name',
                'sku'
            ])
            ->orderBy(['id' => SORT_DESC])
            ->asArray()
            ->all();

        return $this->successEncode($list);
    }

    public function actionAllSelected()
    {
        // boolean to int
        $selected = intval($this->post('selected'));

        $result = Model::updateAll(['selected' => $selected], ['user_id' => $this->user->id]);
        if (false !== $result) {
            return $this->success();
        }

        return $this->fail();
    }

    public function actionItemSelected()
    {
        // boolean to int
        $selected = intval($this->post('selected'));

        $id = $this->post('id');

        $model = Model::findOne(['id' => $id, 'user_id' => $this->user->id]);
        if ($model) {
            $model->selected = $selected;
            if ($model->save()) {
                return $this->success();
            }
        }

        return $this->fail();
    }

    public function actionIncrement()
    {
        $id = $this->post('id');

        $model = Model::findOne(['id' => $id, 'user_id' => $this->user->id]);
        if ($model) {
            $model->quantity += 1;
            $model->selected = 1;
            if ($model->save()) {
                return $this->success();
            }
        }

        return $this->fail();
    }

    public function actionDecrement()
    {
        $id = $this->post('id');

        $model = Model::findOne(['id' => $id, 'user_id' => $this->user->id]);
        if ($model) {
            if ($model->quantity > 0) {
                $model->quantity -= 1;
                if ($model->quantity > 0) {
                    $model->selected = 1;
                }
            }
            if ($model->save()) {
                return $this->success();
            }
        }

        return $this->fail();
    }

    public function actionDeleteCart()
    {
        $result = Model::deleteAll(['user_id' => $this->user->id, 'selected' => 1]);
        if ($result !== false) {
            return $this->success();
        }

        return $this->fail();
    }

    public function actionClearCart()
    {
        $result = Model::deleteAll(['user_id' => $this->user->id]);
        if ($result !== false) {
            return $this->success();
        }

        return $this->fail();
    }

    public function actionGetCartQuantity()
    {
        $count = Model::find()
            ->where(['user_id' => $this->user->id, 'selected' => 1])
            ->sum('quantity');

        return $this->success($count);
    }
}